<template>
  <Dialog v-model="dialogVisible" :appendToBody="true" :scroll="true" title="选择员工">
    <ContentWrap :bodyStyle="{ padding: '0px' }" class="border-none!">
      <div class="h-full flex flex-col justify-between" v-if="list.length > 0">
        <!-- 列表 -->
        <el-row :gutter="10" v-loading="loading">
          <el-col
            :xs="24"
            :sm="24"
            :md="8"
            :lg="12"
            :xl="8"
            v-for="(userItem, index) in list"
            :key="index"
          >
            <SystemUserCard
              :user="userItem"
              v-model:proportion="userItem.proportion"
              :is-active="checkedStatus[userItem.employeeId]"
              @click="SetSelectedUser(userItem)"
          /></el-col>
        </el-row>
      </div>
      <div class="h-full flex flex-col justify-center" v-if="list.length == 0">
        <Empty />
      </div>
    </ContentWrap>
    <template #footer v-if="multiple">
      <el-button type="primary" @click="handleEmitChange">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import * as UserApi from '@/api/shop/system/user/index'

import { propTypes } from '@/utils/propTypes'
import { CHANGE_EVENT } from 'element-plus'
import SystemUserCard from './systemUserCard.vue'
import _ from 'lodash'

/**
 * 员工表格选择对话框
 * 1. 单选模式：
 *    1.1 点击表格左侧的单选框时，结束选择，并关闭对话框
 *    1.2 再次打开时，保持选中状态
 * 2. 多选模式：
 *    2.1 点击表格左侧的多选框时，记录选中的员工
 *    2.2 切换分页时，保持员工的选中的状态
 *    2.3 点击右下角的确定按钮时，结束选择，关闭对话框
 *    2.4 再次打开时，保持选中状态
 */
defineOptions({ name: 'SystemUserSelect' })

const props = defineProps({
  // 多选模式
  multiple: propTypes.bool.def(false)
})

// 列表的数据
const list = ref<any[]>([])
// 列表的加载中
const loading = ref(false)
// 弹窗的是否展示
const dialogVisible = ref(false)
// 查询参数

/** 打开弹窗 */
const open = (userList?: any[]) => {
  // 重置
  checkedUsers.value = []
  checkedStatus.value = {}
  isCheckAll.value = false
  isIndeterminate.value = false

  // 处理已选中
  if (userList && userList.length > 0) {
    checkedUsers.value = [...userList]
    checkedStatus.value = Object.fromEntries(userList.map((user) => [user.employeeId, true]))
    list.value.forEach((element) => {
      let checkedUsersItem = checkedUsers.value.find(
        (item) => item.employeeId === element.employeeId
      )
      if (checkedUsersItem) {
        Object.assign(element, checkedUsersItem)
      }
    })
  }

  dialogVisible.value = true
}
// 提供 open 方法，用于打开弹窗
defineExpose({ open })

/** 查询列表 */

const getList = async () => {
  loading.value = true
  try {
    const data = await UserApi.getEmployeeList()

    if (data.length == 0) {
      return
    }
    list.value = data
    // checkbox绑定undefined会有问题，需要给一个bool值
    list.value.forEach(
      (user) =>
        (checkedStatus.value[user.employeeId] = checkedStatus.value[user.employeeId] || false)
    )

    // 计算全选框状态
    calculateIsCheckAll()
  } finally {
    loading.value = false
  }
}

// 是否全选
const isCheckAll = ref(false)
// 全选框是否处于中间状态：不是全部选中 && 任意一个选中
const isIndeterminate = ref(false)
// 选中的员工
const checkedUsers = ref<any[]>([])
// 选中状态：key为员工ID，value为是否选中
const checkedStatus = ref<Record<string, boolean>>({})

// 选中的员工 Id
const selectedUserId = ref()
/** 单选中时触发 */
const handleSingleSelected = (user: any) => {
  user.proportion = 100
  emits(CHANGE_EVENT, user)
  // 关闭弹窗
  dialogVisible.value = false
  // 记住上次选择的ID
  selectedUserId.value = user.employeeId
}

/** 多选完成 */
const handleEmitChange = () => {
  // 关闭弹窗
  dialogVisible.value = false
  emits(CHANGE_EVENT, [...checkedUsers.value])
}

/** 确认选择时的触发事件 */
const emits = defineEmits<{
  change: [user: any | any[] | any]
}>()

/**
 * 选中一行
 * @param checked 是否选中
 * @param spu 员工
 * @param isCalcCheckAll 是否计算全选
 */
const handleCheckOne = (checked: boolean, user: any, isCalcCheckAll: boolean) => {
  console.log(checked)
  if (checked) {
    checkedUsers.value.push(user)
    checkedStatus.value[user.employeeId] = true
  } else {
    const index = findCheckedIndex(user)
    if (index > -1) {
      checkedUsers.value.splice(index, 1)
      checkedStatus.value[user.employeeId] = false
      isCheckAll.value = false
    }
  }
  calculateRate()
  // 计算全选框状态
  if (isCalcCheckAll) {
    calculateIsCheckAll()
  }
}

// 查找员工在已选中员工列表中的索引
const findCheckedIndex = (user: any) =>
  checkedUsers.value.findIndex((item) => item.employeeId === user.employeeId)
const calculateRate = () => {
  let divisor = checkedUsers.value.length //被除数 参与分成的人数
  let countnum = 0 //分成比例平均分
  if (divisor > 0) {
    countnum = 100 / divisor //分成比例平均分
    let num = Math.floor(countnum * 100) / 100
    let difference = 100 - num * divisor
    let firstRate = Number(num + difference)
    checkedUsers.value.forEach((ele, index) => {
      if (index == 0) {
        ele.proportion = Number(firstRate.toFixed(2))
      } else {
        ele.proportion = Number(num.toFixed(2))
      }
    })
  } else {
    list.value.forEach((ele) => {
      ele.proportion = 0
    })
  }
} //计算分成比例
// 计算全选框状态
const calculateIsCheckAll = () => {
  isCheckAll.value = list.value.every((user) => checkedStatus.value[user.employeeId])
  // 计算中间状态：不是全部选中 && 任意一个选中
  isIndeterminate.value =
    !isCheckAll.value && list.value.some((user) => checkedStatus.value[user.employeeId])
}

/** 选择员工 */
const SetSelectedUser = (user: any) => {
  if (props.multiple) {
    handleCheckOne(!checkedStatus.value[user.employeeId], user, true)
  } else {
    handleSingleSelected(user)
  }
}
/** 初始化 **/
onMounted(async () => {
  await getList()
})
</script>
